package aar.test.tessocr;

import android.Manifest;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.adapter.CabinetListAdapter;
import aar.test.tessocr.adapter.ExporderListAdapter;
import aar.test.tessocr.adapter.UnexporderListAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabinetListMpdel;
import aar.test.tessocr.model.CompanySearchModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.SiteDispatchModel;
import aar.test.tessocr.model.UnexporderListModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

public class PieListActivity extends AppCompatActivity {

    private LinearLayout left_layout;

    private  RadioGroup fileRadioGroup;

    private ListView pie_list;

    private Context mContext;

    private DisplayMetrics dm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pie_list);
        mContext=this;

        left_layout=findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        pie_list=findViewById(R.id.pie_list);


        /*fileRadioGroup=findViewById(R.id.fileRadioGroup);
        fileRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.pieed_list){


                    pieedList();
                }else if(checkedId==R.id.unpied_list){
                    unPieedList(1);

                }
            }
        });*/

//        unPieedList(0);

        pieedList();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        } else {


        }
    }


    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.CALL_PHONE)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();

                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(PieListActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(PieListActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };


    private List<UnexporderListModel> mList = new ArrayList<>();

    private  void unPieedList(final int typp){


        //小1中2大3小

        Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(this, "userId", ""));


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<UnexporderListModel>>>post(Urls.URL_UNEXPORDER_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<UnexporderListModel>>>(PieListActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<UnexporderListModel>>> response) {


//
                        Log.e("MainActivity", "onSuccess111-----logout---------------");


                        if (null != response.body().data && response.body().data.size() > 0) {
                            mList = new ArrayList<>();
                            mList = response.body().data;
                            Log.e("MainActivity", "onSuccess-22----logout---------------" + response.body().data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    UnexporderListAdapter unexporderListAdapter=new UnexporderListAdapter(mContext,mList);
                                    pie_list.setAdapter(unexporderListAdapter);

                                    if(typp==1){
                                        unexporderListAdapter.notifyDataSetChanged();
                                    }

                                    unexporderListAdapter.setViewClickListener(new UnexporderListAdapter.ViewClickListener() {
                                        @Override
                                        public void gridopen(int pos) {
                                            gridOpen(pos);
                                        }

                                        @Override
                                        public void gridconfire(int pos) {
                                            gridConfirem(pos);
                                        }
                                    });


                                }
                            });
                        } else {


                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        Log.e("MainActivity", "onError---------------------");

                    }
                });


    }


    private  void pieedList(){

        //小1中2大3小

        Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(this, "userId", ""));


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<UnexporderListModel>>>post(Urls.URL_EXPORDER_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<UnexporderListModel>>>(PieListActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<UnexporderListModel>>> response) {


//
                        Log.e("MainActivity", "onSuccess111-----logout---------------");


                        if (null != response.body().data && response.body().data.size() > 0) {
                            mList.clear();
                            mList = response.body().data;
                            Log.e("MainActivity", "onSuccess-22----logout---------------" + response.body().data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ExporderListAdapter exporderListAdapter=new ExporderListAdapter(mContext,mList);
                                    pie_list.setAdapter(exporderListAdapter);
                                    exporderListAdapter.notifyDataSetChanged();

                                    exporderListAdapter.setViewClickListener(new ExporderListAdapter.ViewClickListener() {
                                        @Override
                                        public void gridOpen(int pos) {
                                            expordergridOpen(pos);
                                        }

                                        @Override
                                        public void gridTackBack(int pos) {
                                            expordergridGiveBack(pos);
                                            expordergridOpen(pos);
                                        }
                                    });
                                }
                            });
                        } else {


                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        Log.e("MainActivity", "onError---------------------");

                    }
                });


    }


    private void   expordergridOpen(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", mList.get(pos).getCabinetid());
        map.put("type", "0");
        map.put("cabinetGridId", mList.get(pos).getCabinetgridid());
        map.put("adminid", PrefUtils.getString(PieListActivity.this, "userId", ""));

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_EXPUSEROPEN)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        /*JSONObject jsonObject = new JSONObject(response.body());
                        if (jsonObject.has("code")) {
                            String code = jsonObject.getString("code");
                            if (TextUtils.equals(code, "200")) {
                                String msg = jsonObject.getString("msg");
                                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                            } else if (TextUtils.equals(code, "100")) {
                                String msg = jsonObject.getString("msg");
                                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                                pieedList();
                            }
                        }*/
                        pieedList();

                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.e("MainActivity", "onError---------------------");

                    }
                }

        );


    }

    private void   expordergridGiveBack(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("orderid", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_GIVE_BACK)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
                                    pieedList();
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }



    private void gridOpen(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", "3");
        map.put("gridType", mList.get(pos).getGridType() + "");

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_XIANCHANG)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();

                                    String data=jsonObject.getString("data");

                                    if(!TextUtils.isEmpty(data)){
                                        JSONObject dataObject = new JSONObject(data);
                                        String cabinetgridid=dataObject.getString("cabinetgridid");
                                        String cabinetid=dataObject.getString("cabinetid");
                                        String gridnum=dataObject.getString("gridnum");
                                        String isuse=dataObject.getString("isuse");
                                        String currentpassword=dataObject.getString("currentpassword");
                                        String gridtype=dataObject.getString("gridtype");
                                        String sku=dataObject.getString("sku");
                                        String companyid=dataObject.getString("companyid");
                                        String orderid=dataObject.getString("orderid");
                                        String expresspassword=dataObject.getString("expresspassword");

                                        SiteDispatchModel siteDispatchModel=new SiteDispatchModel();
                                        siteDispatchModel.setCabinetgridid(cabinetgridid);
                                        siteDispatchModel.setCabinetid(cabinetid);
                                        siteDispatchModel.setCompanyid(companyid);
                                        siteDispatchModel.setCurrentpassword(currentpassword);
                                        siteDispatchModel.setExpresspassword(expresspassword);
                                        siteDispatchModel.setGridnum(gridnum);
                                        siteDispatchModel.setIsuse(isuse);
                                        siteDispatchModel.setOrderid(orderid);
                                        siteDispatchModel.setGridtype(gridtype);
                                        siteDispatchModel.setSku(sku);


                                        BaseApplication.getIntance().setmSiteDispatchModel(siteDispatchModel);


                                    }
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }



    private void gridConfirem(int pos) {

        if(null==BaseApplication.getIntance().getmSiteDispatchModel()){
            Toast.makeText(PieListActivity.this, "没有柜子信息，请先开柜再确认！", Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.isEmpty(mList.get(pos).getExpress_order())){
            Toast.makeText(mContext, "请输入运单号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(mList.get(pos).getPhone())){
            Toast.makeText(mContext, "请输入电话号", Toast.LENGTH_SHORT).show();
            return;
        }





        Map<String, Object> map = new HashMap<>();
        map.put("cabinetGridId",mList.get(pos).getCabinetgridid());
        map.put("express", mList.get(pos).getExpress_order());
        map.put("phone", mList.get(pos).getPhone());
        map.put("adminid", mList.get(pos).getAdminid());

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse>post(Urls.URL_XIANCHANG_CONFIRM)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(PieListActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {


                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);
                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {

                        Log.e("MainActivity", "onError---------------------");
                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_SHORT).show();
                        }

                    }
                });


    }



}
